package com.uni.crawl.common.util.crawl;

import cn.hutool.core.text.StrPool;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.XmlUtil;
import com.uni.crawl.common.enums.crawl.CrawlTemplateBuildInParamEnum;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class XsltTemplatePiplineBuilder {

    private String seedUrl;
    private String tmpl;

    public static XsltTemplatePiplineBuilder create() {
        return new XsltTemplatePiplineBuilder();
    }

    public XsltTemplatePiplineBuilder seedUrl(String seedUrl) {
        this.seedUrl = seedUrl;
        return this;
    }

    public XsltTemplatePiplineBuilder tmpl(String tmpl) {
        this.tmpl = tmpl;
        return this;
    }

    public XsltTemplatePipline build() {
        String finalTmpl = tmpl;
        if (StrUtil.isEmpty(finalTmpl)) {
            return null;
        }

        if (StrUtil.isNotEmpty(seedUrl)) {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put(CrawlTemplateBuildInParamEnum.SEED_URL.getParam(), seedUrl);
            finalTmpl = StrUtil.format(finalTmpl, paramMap);
        }
        // XML不允许出现&，会出现XML解析异常，所以先转换一次，后续还原
        finalTmpl = StrUtil.replace(finalTmpl, "&", StrPool.HTML_AMP);

        NodeList templateList = XmlUtil.parseXml(finalTmpl).getElementsByTagName("xsl:template");
        XsltTemplatePipline pipline = new XsltTemplatePipline();
        pipline.setTemplateList(new ArrayList<>());
        for (int i = 0; i < templateList.getLength(); i++) {
            Node templateNode = templateList.item(i);
            String templateStr = XmlUtil.toStr(templateNode, CharsetUtil.UTF_8, false, true);
            pipline.getTemplateList().add(templateStr);
        }
        return pipline;
    }

}
